package com.quan.weixin.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.quan.common.base.bean.ResultBean;
import com.quan.common.core.BaseController;
import com.quan.common.utils.RandomUitl;
import com.quan.weixin.entity.WeixinMenu;
import com.quan.weixin.model.Menu;
import com.quan.weixin.service.WeixinMenuService;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import me.chanjar.weixin.mp.api.WxMpService;

@RestController
@RequestMapping(value = "/api/weixin/menu")
public class WeixinMenuController extends BaseController {

	@Autowired
	private WeixinMenuService weixinMenuService;
	
	//@Autowired
	//private WeixinApiService apiService ;
	
	@Autowired
	private WxMpService wxMpService ;

	@PostMapping(value = "/add")
	public Object add(@Valid @RequestBody WeixinMenu entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return ResultBean.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		entity.setEventKey(StringUtils.isNotEmpty(entity.getType()) ? entity.getType().toUpperCase() + "_" + RandomUitl.generateString(5).toUpperCase() : null);
		this.weixinMenuService.insertSelective(entity);

		return ResultBean.ok();
	}

	@GetMapping(value = "/delete/{id}")
	public Object delete(@PathVariable Integer id) {
		this.weixinMenuService.deleteById(id);
		return ResultBean.ok();
	}

	@PostMapping(value = "/update")
	public Object update(@Valid @RequestBody WeixinMenu entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return ResultBean.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		if(entity.getPid() == null) {
			entity.setPid(0);
		}
		this.weixinMenuService.update(entity);

		return ResultBean.ok();
	}

	@GetMapping(value = "/get/{id}")
	public Object list(@PathVariable Integer id) {
		return this.weixinMenuService.selectOneById(id);
	}
	
	@GetMapping(value = "/list")
	public Object list(WeixinMenu entity) {
		Integer pid = 0 ;
		if(entity.getPid() != null) {
			pid = entity.getPid();
		}
		return this.weixinMenuService.selectChildren(pid);
	}

	@GetMapping(value = "/tree")
	public Object tree(WeixinMenu entity) {
		return this.weixinMenuService.tree(entity);
	}
	
	/**
	 * 获取节点的所有父节点
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/getParents")
	public Object getParents(Integer id) {
		return this.weixinMenuService.getParents(id);
	}
	
	/**
	 * 推送菜单到微信
	 * @return
	 */
	@GetMapping(value="/pushMenuToWeiXin")
	public Object pushMenuToWeiXin() {
		
		List<Menu> allMenusToWeixin = this.weixinMenuService.getAllMenusToWeixin();

		Map<String, List<Menu>> map = new HashMap<String, List<Menu>>();
		map.put("button", allMenusToWeixin);
		
		String wxMenuJson = WxGsonBuilder.create().toJson(map) ;
		
		try {
			String menuCreate = this.wxMpService.getMenuService().menuCreate(wxMenuJson);
			if(menuCreate != null) {
				logger.info("微信菜单推送失败：{}", menuCreate);
				return ResultBean.failure(menuCreate);
			} 
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		
		/*ResponseMsg msg = this.apiService.pushMenuToWeiXin(WeixinContext.getAccessToken());
		
		if(msg.getErrcode() > 0) {
			logger.info("微信菜单推送失败：{}", msg.toString());
			return ResultBean.failure(msg.getErrcode() + ":" +msg.getErrmsg());
		} else {
			logger.info("微信菜单推送成功：{}", msg.toString());
			return ResultBean.ok();
		}*/
		
		return ResultBean.ok();
	}
}
